package com.keke.myblogv1.common.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.util.StringUtils;

import java.util.Date;

public class JwtUtil {
    //设置有效期时间
    private static final long EXPIRE_TIME = 5 * 60 * 1000;
    //设置加密秘钥
    private static final String SECRET = "DERRICK";

    //生成jwt
    public static String sign(String userId){
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return JWT.create()
                    .withAudience(userId)
                    .withExpiresAt(date)
                    .sign(algorithm);
        }catch (Exception e){
            return null;
        }
    }

    //获得用户id
    public static String getUserId(String token){
        try {
            String userId=JWT.decode(token).getAudience().get(0);
            return userId;
        }catch (Exception e){
            return null;
        }
    }

    //进行jwt验证
    public static boolean checkSign(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT verify = verifier.verify(token);
            if(StringUtils.isEmpty(verify.getToken())){
                throw new RuntimeException("token 无效，请重新获取");
            }
            return true;
        }catch (JWTVerificationException exception){
            throw new RuntimeException("token 无效，请重新获取");
        }
    }
}
